package com.hdcircles.autoform.ui.main.fragment;

import android.app.ActivityOptions;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hdcircles.autoform.R;
import com.hdcircles.autoform.base.BaseFragment;
import com.hdcircles.autoform.model.bean.User;
import com.hdcircles.autoform.presenter.UserPresenter;
import com.hdcircles.autoform.presenter.contract.UserContract;
import com.hdcircles.autoform.ui.label.activity.ImageActivity;
import com.hdcircles.autoform.ui.main.activity.LoginActivity;
import com.hdcircles.autoform.util.SharedPreferenceUtil;
import com.hdcircles.autoform.util.SnackbarUtil;
import com.hdcircles.autoform.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 *
 * Created by hdcircles on 2016/11/16.
 */

public class UserFragment extends BaseFragment<UserPresenter> implements UserContract.View {


    @BindView(R.id.iv_user)
    CircleImageView ivUser;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    private boolean isEdit;

    private User mUser;

    public static final String USER_QUIT_ACTION="com.hdcircles.autoform.ui.main.fragment.QUIT_ACTION";
    private ProgressDialog dialog;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_user;
    }

    @Override
    protected void initEventAndData() {
        mPresenter.getUser(SharedPreferenceUtil.getUserEmail());
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.user_menu,menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==R.id.action_quit){
            AlertDialog.Builder builder=new AlertDialog.Builder(getContext())
                    .setTitle("提示")
                    .setMessage("确认退出当前用户？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            SharedPreferenceUtil.setUserEmail("");
                            SharedPreferenceUtil.setUserName("");
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            getActivity().sendBroadcast(new Intent(USER_QUIT_ACTION));
                            getActivity().finish();
                        }
                    })
                    .setNegativeButton("取消",null);
            builder.show();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showUser(User user) {
        mUser=user;
        if (null!=user.getName()) {
            etName.setText(user.getName());
            SharedPreferenceUtil.setUserName(user.getName());
        }
        if (null!=user.getPassword()) etPassword.setText(user.getPassword());
        if (null!=user.getEmail()) etEmail.setText(user.getEmail());
        if (null!=user.getPhoto()) {
            Glide.with(this)
                    .load(user.getPhoto())
                    .into(ivUser);
        }
        if ("".equals(SharedPreferenceUtil.getUserName())){
            ToastUtil.shortShow("请完善用户信息");
        }
    }

    @Override
    public void editUserSuccess(String msg) {
        closeProgress();
        ToastUtil.shortShow(msg);
        if (0!=etName.getText().length()){
            SharedPreferenceUtil.setUserName(etName.getText().toString().trim());
        }
    }

    @Override
    public void notifyChange() {
        closeProgress();
    }

    @Override
    public void showError(String msg) {
        SnackbarUtil.showShort(ivUser,msg);
    }

    @OnClick(R.id.tv_edit)
    void editUserInfo(){
        if (!isEdit){
            tvEdit.setText("完成");
            isEdit=true;
            editStatus();
        }else {
            tvEdit.setText("修改");
            isEdit=false;
            editStatus();
            String name=etName.getText().toString();
            String password=etPassword.getText().toString();
            if (name.length()!=0||password.length()!=0){
                showProgress("正在修改");
                if (name.length()!=0) mUser.setName(name);
                if (password.length()!=0) mUser.setPassword(password);
                mPresenter.editUser(mUser);
            }
        }
    }

    @OnClick(R.id.iv_user)
    void pickUserPhoto(){
        if (isEdit){
            RxGalleryFinal.with(getContext())
                    .image()
                    .radio()
                    .imageLoader(ImageLoaderType.GLIDE)
                    .subscribe(new RxBusResultSubscriber<ImageRadioResultEvent>() {
                        @Override
                        protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                            String path = imageRadioResultEvent.getResult().getOriginalPath();
                            Bitmap bitmap = BitmapFactory.decodeFile(path);
                            ivUser.setImageBitmap(bitmap);
                            mPresenter.uploadImage(path,mUser);
                        }
                    })
                    .openGallery();
            return;
        }
        if (null!=mUser.getPhoto()){
            Intent i=new Intent(getActivity(),ImageActivity.class);
            i.putExtra("imageUrl",mUser.getPhoto());
            ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(getActivity(),ivUser,"shareView");
            startActivity(i,options.toBundle());
        }
    }

    private void editStatus() {
        etName.setClickable(isEdit);
        etName.setFocusableInTouchMode(isEdit);
        etName.clearFocus();
        etPassword.setClickable(isEdit);
        etPassword.setFocusableInTouchMode(isEdit);
        etPassword.clearFocus();
//        ivUser.setClickable(isEdit);
        ivUser.clearFocus();
    }

    private void showProgress(String msg){
        dialog = new ProgressDialog(getContext(), R.style.AppTheme_Dark_Dialog);
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.setMessage(msg);
        dialog.show();
    }

    private void closeProgress(){
        if (null!=dialog&&dialog.isShowing()){
            dialog.dismiss();
        }
    }




}
